<template>
  <div class="xw-lazy">
    <h2>懒加载图片、图片转base64、srcset</h2>
    <img 
        id="tobase"
        :src="imgList[2]"
        alt=""
        width="300px"
        :srcset="srcset">
    <img
        v-lazy="item"
        v-for="item in imgList"
        :key="item"
        class="xw-lazy__img"
        width="200px"
        height="auto">
    </img>
  </div>
</template>

<script setup lang="ts">
import { use2Base64 } from '@/hooks/use2Base64';
import {
    // Directive,
    //  DirectiveBinding,
    //   Ref,
       computed,
        // onMounted,
         ref} from 'vue'
// const defaultImg = await import('@/assets/vue.svg')
// .then(res => {
//     console.log(res);
//     return res?.default
// })
// console.log('defaultImg',defaultImg.default);

    const imgList = ref<string[]>([
        // defaultImg.default
    ])
    type imgType = {
    default: string
}
const srcset = computed(() => {
    return `${imgList.value[9]} 1x,${imgList.value[6]} 2x,${imgList.value[7]} 3x`
})
 // 将img转为base64
 use2Base64('#tobase').then(res => {
    console.log('res',res.basestr);
    // const curimg = document.querySelector('#tobase') as HTMLImageElement
    // curimg.src = res?.basestr
})   
    



// 注册懒加载指令v-lazy去控制img Record定义对象的key和value类型
// import.meta.glob异步引入资源返回promise数组 erger:true相当于静态引入直接import
const beautys:Record<string, imgType> = import.meta.glob('@/assets/beauty/*.*', {eager: true})
    console.log('beautys',beautys);
    imgList.value = Object.values(beautys).map(item => item.default)
    // const vLazy:Directive = async (el:HTMLImageElement, binding:DirectiveBinding) => {
    //     // el.src 去设置默认图片
    //     const defimg = await import('@/assets/vue.svg')
        
    //     el.src = defimg.default

    //     // 监听new IntersectionObserver(enr) 
    //     const obser = new IntersectionObserver((enr) => {
    //         console.log('enr',enr);
    //         const curEnr = enr[0]
    //     // 去监听img是否在视口内，在enr.radtio > 0 此时替换图片 同时关闭监听
    //         if(curEnr.intersectionRatio > 0) {
    //             console.log('进入视野');
    //             setTimeout(() => {
    //                 el.src = binding.value
    //             },2000)
    //             obser.unobserve(el)
    //         }
    //     })
    //     obser.observe(el)
    // }
</script>

<style lang="scss" scoped>
@include b(lazy) {
    display: flex;
    flex-flow: column wrap;
}   
</style>
